package com.ilink.groundservice.service.impl.AiX;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.AiX.*;
import com.ilink.groundservice.entity.VO.AiX.AiXAuthorResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXProjectResponse;
import com.ilink.groundservice.mapper.AiX.*;
import com.ilink.groundservice.service.AiX.AiXProjectService;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkapi.dto.ground.AiX.*;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.service.oss.MinioService;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AiXProjectServiceImpl implements AiXProjectService {

    private final AiXProjectMapper aiXProjectMapper;

    private final AiXProjectAuthorMapper aiXProjectAuthorMapper;

    private final AiXTagMapper aiXTagMapper;

    private final AiXTagConnectMapper aiXTagConnectMapper;

    private final MinioService minioService;

    private final UserServiceClient userServiceClient;


    @Override
    public IPage<AiXProjectResponse> getProjects(AiXAreaFilterRequest request){
        // 创建分页对象
        Page<AiXProject> page = new Page<>(request.getPage(), request.getSize());
        LambdaQueryWrapper<AiXProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(request.getAreaId() != null, AiXProject::getAreaId, request.getAreaId());
        if (request.getTag() != null && !request.getTag().isEmpty()) {
            List<Long> projectIdsWithTag = aiXTagConnectMapper.selectList(
                    new LambdaQueryWrapper<AiXTagConnect>().eq(AiXTagConnect::getTagId,
                            aiXTagMapper.selectOne(new LambdaQueryWrapper<AiXTag>().eq(AiXTag::getTagName, request.getTag()).last("LIMIT 1")).getTagId())
            ).stream().map(AiXTagConnect::getConnectTableKey).collect(Collectors.toList());

            if (!projectIdsWithTag.isEmpty()) {
                queryWrapper.in(AiXProject::getProjectId, projectIdsWithTag);
            } else {
                return new Page<>(request.getPage(), request.getSize()); // 如果没有匹配的标签，返回空结果
            }
        }
//        if (!request.getKeyword().isEmpty()) {
//            queryWrapper.and(wrapper -> {
//                // 调用外部服务，根据传入的名字进行模糊查询，获取匹配的 userId 列表
//                List<String> userIds = getUserIdsByRealNameLike(request.getKeyword());
//
//                if (!userIds.isEmpty()) {
//                    // 如果找到了对应的 userId，则查询与这些 userId 相关联的项目
//                    List<Long> projectIdsWithAuthors = aiXProjectAuthorMapper.selectList(
//                            new LambdaQueryWrapper<AiXProjectAuthor>()
//                                    .in(AiXProjectAuthor::getUserId, userIds)  // 根据 userId 查询
//                    ).stream().map(AiXProjectAuthor::getProjectId).collect(Collectors.toList());
//
//                    // 如果有匹配的项目 ID，则添加到查询条件中
//                    if (!projectIdsWithAuthors.isEmpty()) {
//                        wrapper.like(AiXProject::getProjectTitle, request.getKeyword())  // 项目标题模糊匹配
//                                .or().like(AiXProject::getIntroduction, request.getKeyword())  // 简介模糊匹配
//                                .or().in(AiXProject::getProjectId, projectIdsWithAuthors);  // 项目 ID 与作者匹配
//                    } else {
//                        wrapper.like(AiXProject::getProjectTitle, request.getKeyword())
//                                .or().like(AiXProject::getIntroduction, request.getKeyword());
//                    }
//                } else {
//                    // 如果没有找到匹配的 userId，则直接进行项目标题和简介的模糊匹配
//                    wrapper.like(AiXProject::getProjectTitle, request.getKeyword())
//                            .or().like(AiXProject::getIntroduction, request.getKeyword());
//                }
//            });
//        }
        if (!request.getKeyword().isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like(AiXProject::getProjectTitle, request.getKeyword())
                            .or().like(AiXProject::getIntroduction, request.getKeyword())
            );
        }

        // 执行查询
        IPage<AiXProject> projectPage = aiXProjectMapper.selectPage(page, queryWrapper);
        //构建响应
        List<AiXProjectResponse> responseList = projectPage.getRecords().stream()
                .map(project -> {
                    AiXProjectResponse response = new AiXProjectResponse();
                    response.setProjectId(project.getProjectId());
                    String imagePath = minioService.getBucketFileUrl("dataset-square-migrate",project.getCoverUrl());
                    if(imagePath == null){
                        log.error("项目封面未找到"+project.getCoverUrl());
                        return null;
                    }
                    List<AiXProjectAuthor> authors = aiXProjectAuthorMapper.selectList(new QueryWrapper<AiXProjectAuthor>().eq("project_id", project.getProjectId()));
                    List<AiXAuthorResponse> authorsResponseList = authors.stream()
                            .map(author -> getUserInfoById(author.getUserId()))  // 获取用户所有信息
                            .filter(Objects::nonNull)  // 过滤掉为空的用户信息
                            .collect(Collectors.toList());

                    response.setCoverUrl(imagePath);
                    response.setProjectTitle(project.getProjectTitle());
                    response.setIntroduction(project.getIntroduction());
                    response.setAuthors(authorsResponseList);
                    response.setAreaId(project.getAreaId());
                    response.setTargetUrl(project.getTargetUrl());
                    // 获取项目标签并转换为字符串列表
                    List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(new LambdaQueryWrapper<AiXTagConnect>().eq(AiXTagConnect::getConnectTableKey, project.getProjectId()));
                    List<String> tags = tagConnects.stream()
                            .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
                            .collect(Collectors.toList());
                    response.setTags(tags); // 设置标签列表
                    return response;
                })
                .collect(Collectors.toList());

        // 创建分页响应
        Page<AiXProjectResponse> responsePage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());
        responsePage.setRecords(responseList);

        return responsePage;
    }

    @Override
    @Transactional
    public R insertProject(AiXProjectInsertRequest request){
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        Long projectId = idGenerator.nextId();
        AiXProject project = new AiXProject();
        project.setProjectId(projectId);
        project.setProjectTitle(request.getProjectTitle());
        project.setIntroduction(request.getIntroduction());
        project.setAreaId(request.getAreaId());
        project.setTargetUrl(request.getTargetUrl());

        String objectName = "area/"+request.getAreaId()+"/project/"+projectId+ getFileExtension(request.getCoverImage().getOriginalFilename());

        boolean isUploaded = minioService.uploadBucketFile(request.getCoverImage(), "dataset-square-migrate", objectName);
        if (!isUploaded) {
            return R.error("项目封面上传失败");
        }
        project.setCoverUrl(objectName);
        aiXProjectMapper.insert(project); // 插入项目

        //插入作者表
        if (request.getAuthors() != null) {
            for (String author : request.getAuthors()) {
                boolean isInsert = detectUserInfoById(author);
                if (!isInsert) {
                    throw new RuntimeException("userid为" + author + "的作者不存在");
                }
                AiXProjectAuthor projectAuthor = new AiXProjectAuthor();
                projectAuthor.setUserId(author);
                projectAuthor.setProjectId(projectId);
                projectAuthor.setProjectAuthorId(idGenerator.nextId());
                aiXProjectAuthorMapper.insert(projectAuthor);
            }
        }

        //插入标签
        if (request.getTags() != null) {
            handleTags(request.getTags(), projectId);
        }
        return R.ok("项目插入成功");
    }

    @Override
    @Transactional
    public R updateProject(AiXProjectUpdateRequest request){
        Long projectId = request.getProjectId();
        AiXProject project = new AiXProject();
        project.setProjectId(projectId);
        project.setProjectTitle(request.getProjectTitle());
        project.setIntroduction(request.getIntroduction());
        project.setAreaId(request.getAreaId());
        project.setTargetUrl(request.getTargetUrl());
        aiXProjectMapper.updateById(project);
        List<AiXProjectAuthor> existingAuthors = aiXProjectAuthorMapper.selectList(new LambdaQueryWrapper<AiXProjectAuthor>().eq(AiXProjectAuthor::getProjectId, projectId));
        Set<String> existingUserIds = existingAuthors.stream().map(AiXProjectAuthor::getUserId).collect(Collectors.toSet());
        Set<String> newUserIds = new HashSet<>();

        // 删除当前项目的所有标签
        aiXTagConnectMapper.delete(new LambdaQueryWrapper<AiXTagConnect>()
                .eq(AiXTagConnect::getConnectTableKey, projectId)
                .eq(AiXTagConnect::getConnectTable, "ai_x_project"));
        // 处理新的标签
        if (request.getAiXProjectTags() != null) {
            handleTags(request.getAiXProjectTags(), projectId); // 调用提取的标签处理方法
        }

        // 处理新的作者
        if (request.getAiXProjectAuthors() != null) {
            for (String userId : request.getAiXProjectAuthors()) {
                newUserIds.add(userId);
                if(!existingUserIds.contains(userId)){
                    boolean isInsert = detectUserInfoById(userId);
                    if (!isInsert) {
                        throw new RuntimeException("userid为" + userId + "的作者不存在");
                    }
                        AiXProjectAuthor projectAuthor = new AiXProjectAuthor();
                        projectAuthor.setProjectId(projectId);
                        projectAuthor.setProjectAuthorId(new SnowflakeIdGenerator(1, 1).nextId());
                        projectAuthor.setUserId(userId);
                        aiXProjectAuthorMapper.insert(projectAuthor);
                }
            }
        }
        for (AiXProjectAuthor existingAuthor : existingAuthors) {
            if (!newUserIds.contains(existingAuthor.getUserId())) {
                aiXProjectAuthorMapper.deleteById(existingAuthor.getProjectAuthorId());
            }
        }


        return R.ok("项目更新成功");
    }
    @Override
    @Transactional
    public R updateProjectCover(MultipartFile file, Long projectId, Long areaId) {
        String objectName = "area/" + areaId + "/project/" + projectId + getFileExtension(file.getOriginalFilename());
        boolean isUploaded = minioService.uploadBucketFile(file, "dataset-square-migrate", objectName);
        if (!isUploaded) {
            return R.error("项目封面更新失败");
        }
        // 查询项目对象
        AiXProject project = aiXProjectMapper.selectById(projectId);
        if (project == null) {
            return R.error("项目未找到");
        }
        // 更新封面 URL
        project.setCoverUrl(objectName);
        aiXProjectMapper.updateById(project);
        return R.ok("项目封面更新成功");
    }


    @Override
    @Transactional
    public void deleteProject(Long projectId) {
        try {
            AiXProject project = aiXProjectMapper.selectById(projectId);
            if (project != null) {
                String coverUrl = project.getCoverUrl();
                // 查找最后一个斜杠的位置
                int lastSlashIndex = coverUrl.lastIndexOf('/');
                // 使用substring方法进行拆分
                String directory = coverUrl.substring(0, lastSlashIndex + 1);
                String fileName = coverUrl.substring(lastSlashIndex + 1);
                boolean isDeleted = minioService.deleteBucketFile("dataset-square-migrate",directory, fileName);
                if (!isDeleted) {
                    log.error("删除OSS对象失败，项目ID: {}", projectId);
                }
                // 删除当前项目的所有标签
                aiXTagConnectMapper.delete(new LambdaQueryWrapper<AiXTagConnect>()
                        .eq(AiXTagConnect::getConnectTableKey, projectId)
                        .eq(AiXTagConnect::getConnectTable, "ai_x_project"));
                //删除当前项目的作者
                aiXProjectAuthorMapper.delete(new LambdaQueryWrapper<AiXProjectAuthor>()
                        .eq(AiXProjectAuthor::getProjectId, projectId));
            }
            // 删除数据库条目
            aiXProjectMapper.deleteById(projectId);
        } catch (Exception e) {
            log.error("删除项目失败，项目ID: {}", projectId, e);
            throw e;
        }
    }
    @Override
    public AiXProjectResponse getProject(Long projectId) {
        AiXProject project = aiXProjectMapper.selectById(projectId);
        // 使用 AiXTagConnect 获取标签
        List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(
                new LambdaQueryWrapper<AiXTagConnect>()
                        .eq(AiXTagConnect::getConnectTableKey, projectId)
                        .eq(AiXTagConnect::getConnectTable, "ai_x_project")
        );
        List<AiXTag> tags = tagConnects.stream()
                .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()))
                .collect(Collectors.toList());

        List<AiXProjectAuthor> authors = aiXProjectAuthorMapper.selectList(new QueryWrapper<AiXProjectAuthor>().eq("project_id", projectId));
        AiXProjectResponse response = new AiXProjectResponse();
        response.setProjectId(project.getProjectId());
        String imagePath = minioService.getBucketFileUrl("dataset-square-migrate",project.getCoverUrl());
        if(imagePath == null){
            log.error("项目封面未找到"+project.getCoverUrl());
            return null;
        }

        List<AiXAuthorResponse> authorsResponseList = authors.stream()
                .map(author -> getUserInfoById(author.getUserId()))  // 获取用户所有信息
                .filter(Objects::nonNull)  // 过滤掉为空的用户信息
                .collect(Collectors.toList());

        response.setCoverUrl(imagePath);
        response.setProjectTitle(project.getProjectTitle());
        response.setIntroduction(project.getIntroduction());
        response.setAuthors(authorsResponseList);
        response.setAreaId(project.getAreaId());
        response.setTargetUrl(project.getTargetUrl());
        response.setTags(tags.stream().map(AiXTag::getTagName).collect(Collectors.toList()));

        return response;
    }
    @Override
    public List<String> getProjectTags(Long areaId) {
        return aiXTagConnectMapper.getProjectTags(areaId, 8);
    }

    private void handleTags(List<String> tags, Long projectId) {
        for (String tag : tags) {
            // 检查标签是否已存在
            AiXTag existingTag = aiXTagMapper.selectOne(new LambdaQueryWrapper<AiXTag>().eq(AiXTag::getTagName, tag).last("LIMIT 1"));
            Long tagId;
            if (existingTag == null) {
                // 标签不存在，生成随机ID并插入新标签
                tagId = new SnowflakeIdGenerator(1, 1).nextId();
                AiXTag newTag = new AiXTag();
                newTag.setTagId(tagId);
                newTag.setTagName(tag);
                aiXTagMapper.insert(newTag); // 插入新标签
            } else {
                // 标签已存在，使用现有的tagId
                tagId = existingTag.getTagId();
            }

            // 在连接表中插入关联
            AiXTagConnect tagConnect = new AiXTagConnect();
            tagConnect.setConnectId(new SnowflakeIdGenerator(1, 1).nextId()); // 生成连接表主键
            tagConnect.setConnectTable("ai_x_project");
            tagConnect.setConnectTableKey(projectId);
            tagConnect.setTagId(tagId);
            aiXTagConnectMapper.insert(tagConnect); // 插入关联
        }
    }


    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return dotIndex == -1 ? "" : fileName.substring(dotIndex);
    }

    private AiXAuthorResponse getUserInfoById(String userId) {
        // 获取用户信息
        R whoami = userServiceClient.whoami(userId);
        HttpStatus status = HttpStatus.valueOf(whoami.getCode());

        if (!status.is2xxSuccessful()) {
            log.error(String.format("获取用户信息失败，用户ID: %s", userId));
            return null; // 如果获取用户信息失败，返回 null
        }

        // 获取用户详细信息
        User userDetail = BeanUtils.copyBean(whoami.getData(), User.class);
        // 将用户信息映射到 AiXAuthorResponse
        AiXAuthorResponse authorResponse = new AiXAuthorResponse();
        authorResponse.setUserId(userDetail.getUserId());
        authorResponse.setNickname(userDetail.getNickname());
        authorResponse.setSchoolName(userDetail.getSchoolName());
        authorResponse.setEmail(userDetail.getEmail());
        authorResponse.setSchoolId(userDetail.getSchoolId());
        authorResponse.setUserIntroduction(userDetail.getUserIntroduction());
        authorResponse.setUserImage(userDetail.getUserImage());
        authorResponse.setUserCollege(userDetail.getUserCollege());
        authorResponse.setUserType(userDetail.getUserType());
        authorResponse.setRealname(userDetail.getRealname());
        authorResponse.setSex(userDetail.getSex());
        authorResponse.setUserGrade(userDetail.getUserGrade());
        authorResponse.setUserMajor(userDetail.getUserMajor());
        authorResponse.setUserMobile(userDetail.getUserMobile());
        authorResponse.setUserCover(userDetail.getUserCover());
        return authorResponse;
    }
//    private List<String> getUserIdsByRealNameLike(String query) {
//        // 调用外部服务，根据 query 进行模糊查询
//        R response = userServiceClient.searchUserByRealName(query);  // 调用外部服务
//
//        // 判断服务返回是否成功
//        HttpStatus status = HttpStatus.valueOf(response.getCode());
//        if (!status.is2xxSuccessful()) {
//            log.error(String.format("根据 realname 模糊查询获取用户信息失败，查询关键字: %s", query));
//            return Collections.emptyList();  // 返回空列表
//        }
//        List<User> userDetails = (List<User>) response.getData();
//        // 创建一个新的列表，用于存放提取的 realname
//        List<String> realnames = new ArrayList<>();
//
//        // 遍历 userDetails，逐个使用 BeanUtils.copyBean 进行转换
//        for (User user : userDetails) {
//            User userCopy = BeanUtils.copyBean(user, User.class);  // 使用 copyBean 方法转换
//            if (userCopy != null) {
//                realnames.add(userCopy.getRealname());  // 提取 realname 并加入到列表中
//            }
//        }
//        // 返回 realname 列表
//        return realnames.isEmpty() ? Collections.emptyList() : realnames;
//    }
    private boolean detectUserInfoById(String userId){
        // 获取用户信息
        R whoami = userServiceClient.whoami(userId);
        HttpStatus status = HttpStatus.valueOf(whoami.getCode());

        if (!status.is2xxSuccessful()) {
            log.error(String.format("获取用户信息失败，用户ID: %s", userId));
            return false; // 如果获取用户信息失败，返回 null
        }
        User userDetail = BeanUtils.copyBean(whoami.getData(), User.class);
        if (userDetail == null){
            return false;
        }
        else return true;
    }

}

